package boofbridgeimaj.examples;

import boofbridgeimaj.image.feature.util.EngineToDetectDescribePoint_F32_TU8;
import boofcv.abst.feature.detdesc.DetectDescribePoint;
import boofcv.core.image.ConvertBufferedImage;
import boofcv.gui.feature.FancyInterestPointRender;
import boofcv.gui.image.ShowImages;
import boofcv.io.image.UtilImageIO;
import boofcv.struct.feature.TupleDesc_U8;
import boofcv.struct.image.ImageFloat32;
import georegression.struct.point.Point2D_F64;
import org.openimaj.image.feature.local.engine.DoGSIFTEngine;

import com.twelvemonkeys.io.FileUtil;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Peter Abeles
 * @author Sina Samangooei (ss@ecs.soton.ac.uk)
 */
public class ExampleImajSiftInBoofCV {

	/**
	 * @param args
	 */
	public static void main( String args[] ) {
		// Reading the image as a resource so the png can be packaged up and the example still work.
		File f;
		String imagePath = "/sunflowers.png";
		try {
			f = File.createTempFile("image", ".png");
			f.deleteOnExit();
			InputStream imgStream = ExampleImajSiftInBoofCV.class.getResourceAsStream(imagePath);
			if(imgStream == null){
				throw new IOException("Image resource does not exist");
			}
			FileUtil.copy(imgStream, new FileOutputStream(f));
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		

		// Create the OpenIMAJ SIFT feature detector/descriptor
		DoGSIFTEngine engine = new DoGSIFTEngine();
		engine.getOptions().setDoubleInitialImage(false);
		engine.getOptions().setMagnitudeThreshold(25);

		int numSpacialBins = engine.getOptions().getNumSpatialBins();
		int length = numSpacialBins*numSpacialBins*engine.getOptions().getNumOriBins();

		// Use a wrapper so that it can be used by BoofCV's equivalent interface
		DetectDescribePoint<ImageFloat32,TupleDesc_U8> boofFeature
				= new EngineToDetectDescribePoint_F32_TU8(engine,length);

		// load and process the image
		BufferedImage image = UtilImageIO.loadImage(f.getAbsolutePath());
		ImageFloat32 input = ConvertBufferedImage.convertFrom(image,(ImageFloat32)null);

		System.out.println("Detecting SIFT features");

		boofFeature.detect(input);

		System.out.println("Displaying results: found = "+boofFeature.getNumberOfFeatures());

		// Display the results
		FancyInterestPointRender render = new FancyInterestPointRender();

		for( int i = 0; i < boofFeature.getNumberOfFeatures(); i++ ) {
			Point2D_F64 p = boofFeature.getLocation(i);
			double scale = boofFeature.getScale(i);
			double ori = boofFeature.getOrientation(i);

			int radius = (int)(scale*3.0);
			render.addCircle((int)p.x,(int)p.y,radius,Color.RED,ori);
		}

		Graphics2D g2 = image.createGraphics();
		g2.setStroke(new BasicStroke(3));
		render.draw(g2);

		ShowImages.showWindow(image,"OpenIMAJ SIFT in BoofCV");
	}
}
